package com.frkj.yuan.activity;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatRatingBar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.frkj.yuan.R;
import com.frkj.yuan.adapter.GridImageAdapter;
import com.frkj.yuan.adapter.OrderCommentAdapter;
import com.frkj.yuan.api.category.OrderCommentCategory;
import com.frkj.yuan.api.presenter.OrderCommentPresenter;
import com.frkj.yuan.base.BaseActivity;
import com.frkj.yuan.base.BaseBean;
import com.frkj.yuan.data.YuyueKeshiDataUtils;
import com.frkj.yuan.entity.MultipleChoose;
import com.frkj.yuan.listener.OnItemClickListener;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.utils.FullScreenUtils;
import com.frkj.yuan.utils.SPUtils;
import com.frkj.yuan.utils.ToastUtil;
import com.frkj.yuan.view.FullyGridLayoutManager;
import com.frkj.yuan.view.GlideEngine;
import com.frkj.yuan.view.RecyclerViewLayoutManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.permissions.PermissionChecker;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.ScreenUtils;
import com.luck.picture.lib.tools.SdkVersionUtils;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 信息说明: 订单点评
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/3/8 15:18:19
 * 项目名称：yuanban
 */
public class OrderCommentActivity extends BaseActivity implements OrderCommentCategory.View {
    private static List<LocalMedia> mIconlist;
    @BindView(R.id.base_title)
    TextView mTIleMsg;
    @BindView(R.id.upload_image)
    RecyclerView mRecyclerView;
    @BindView(R.id.obl_msg)
    TextView mOrderName;
    @BindView(R.id.name)
    TextView mName;
    @BindView(R.id.keshi)
    TextView mKeshiName;
    @BindView(R.id.shijian)
    TextView mShijian;
    @BindView(R.id.check_box)
    CheckBox mCheckBox;
    @BindView(R.id.edit_content)
    EditText mEditText;
    @BindView(R.id.raging_pingjia)
    AppCompatRatingBar mPingjiaRatingBar;
    @BindView(R.id.raging_taidu)
    AppCompatRatingBar mTaiduRatingBar;
    @BindView(R.id.raging_jishu)
    AppCompatRatingBar mJishuRatingBar;
    @BindView(R.id.fwpf)
    TextView mFfwupingfen;
    @BindView(R.id.jspf)
    TextView mJspf;
    @BindView(R.id.ztmsg)
    TextView ztmsg;
    @BindView(R.id.recycler_comment)
    RecyclerView mTitleRecyclerView;
    private GridImageAdapter mAdapter;
    private int maxSelectNum = 9;
    private long orderId;
    private int isAnonymous;
    private float ratingPingjia;
    private float ratingJishu;
    private float ratingTaidu;
    private OrderCommentPresenter mPresenter;
    private String mToken;
    private long mUserId;
    private String orderNo;
    private OrderCommentAdapter mRecyclerAdapter;

    public static Set<Integer> positionSet = new HashSet<>();
    private boolean selectMode = true; //选择模式 多选或者单选  true  多选
    public Set<String> checkTYpeNameSet = new HashSet<>();
    private List<MultipleChoose> mlist;
    private String tagStr;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FullScreenUtils.getInstance().fullScreen(OrderCommentActivity.this, true);
        if (savedInstanceState != null) {
        } else {
            clearCache();
        }
        RecyclerViewLayoutManager.setGridLayoutManager(OrderCommentActivity.this, mTitleRecyclerView, 3);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(4,
                ScreenUtils.dip2px(this, 8), false));
        mAdapter = new GridImageAdapter(OrderCommentActivity.this, onAddPicClickListener);
        if (savedInstanceState != null && savedInstanceState.getParcelableArrayList("selectorList") != null) {
            mAdapter.setList(savedInstanceState.getParcelableArrayList("selectorList"));
        }
        mAdapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((v, position) -> {
            List<LocalMedia> selectList = mAdapter.getData();
            if (selectList.size() > 0) {
                PictureSelector.create(OrderCommentActivity.this)
                        .themeStyle(R.style.picture_default_style) // xml设置主题
                        .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                        .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                        .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .openExternalPreview(position, selectList);
            }
        });
    }
    /**
     * 清空缓存包括裁剪、压缩、AndroidQToPath所生成的文件，注意调用时机必须是处理完本身的业务逻辑后调用；非强制性
     */
    private void clearCache() {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        if (PermissionChecker.checkSelfPermission(OrderCommentActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            PictureFileUtils.deleteAllCacheDirFile(OrderCommentActivity.this);
        } else {
            PermissionChecker.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PictureConfig.APPLY_STORAGE_PERMISSIONS_CODE);
        }
    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_order_comment;
    }

    @Override
    public void initLayoutView() {
        orderNo = getIntent().getStringExtra("orderNo");
        mOrderName.setText("服务项目 : " + (String) getIntent().getStringExtra("fuwuState"));
        mName.setText("就诊人 : " + (String) getIntent().getStringExtra("name"));
        orderId = (long) getIntent().getLongExtra("orderId", 0);
        mKeshiName.setText("科室 : " + (String) getIntent().getStringExtra("keshi"));
        mShijian.setText((String) getIntent().getStringExtra("shijian"));
        mTIleMsg.setText("点评");
        initRatingOnClick();
        initAdapter();
        mToken = (String) SPUtils.get(OrderCommentActivity.this, ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = OrderCommentActivity.this.getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        mPresenter = new OrderCommentPresenter(this);
        SetPersenter(mPresenter);
    }
    private void initAdapter() {
       mlist = YuyueKeshiDataUtils.getCommentList();
        mRecyclerAdapter = new OrderCommentAdapter(OrderCommentActivity.this, mlist);
        mTitleRecyclerView.setAdapter(mRecyclerAdapter);
        mRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                addOrRemove(position);
            }
        });
    }
    private void addOrRemove(int position) {
        if (positionSet.contains(position)) {
            // 如果包含，则撤销选择
            positionSet.remove(position);
            checkTYpeNameSet.remove(mlist.get(position).getName());
        } else {
            // 如果不包含，则添加
            positionSet.add(position);
            checkTYpeNameSet.add(mlist.get(position).getName());
        }
        if (positionSet.size() == 0) {
            // 如果没有选中任何的item，则退出多选模式
            mRecyclerAdapter.notifyDataSetChanged();
            selectMode = false;
        } else {
            // 更新列表界面，否则无法显示已选的item
            mRecyclerAdapter.notifyDataSetChanged();
        }
        StringBuffer sb = new StringBuffer();
        if (checkTYpeNameSet.size()>0){
            Iterator<String> iterator = checkTYpeNameSet.iterator();
            while (iterator.hasNext()){
                String next = iterator.next();
                if (sb.toString().length() == 0) {
                    sb.append(next);
                }
                else {
                    sb.append("&").append(next);
                }
            }
        }
         tagStr = sb.toString();
    }
    /**
     *
     */
    private void initRatingOnClick() {
        mJishuRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                mJspf.setText(rating + " 分");
            }
        });
        mPingjiaRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                ztmsg.setText(rating + " 分");
            }
        });
        mTaiduRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                mFfwupingfen.setText(rating + " 分");
            }
        });
    }

    @OnClick({R.id.base_back, R.id.submit_comment})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finishWitchAnimation();
                break;
            case R.id.submit_comment:
                if (mCheckBox.isChecked() == true) {
                    isAnonymous = 1;
                } else {
                    isAnonymous = 0;
                }
                String content = mEditText.getText().toString().trim();
                ratingJishu = mJishuRatingBar.getRating();
                ratingPingjia = mPingjiaRatingBar.getRating();
                ratingTaidu = mTaiduRatingBar.getRating();
                float number = (ratingJishu + ratingPingjia + ratingTaidu) / 3;
                BigDecimal b = new BigDecimal(number);
                //保留2位小数
                float mScoreNumber = b.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                if (checkTYpeNameSet.size()==0){
                     ToastUtil.showToastINFO(OrderCommentActivity.this,"请最少选择一个服务类型");
                    return;
                }else if (mIconlist!=null&&mIconlist.size()> 0){
                    mPresenter.getOrderComment(mToken, mUserId, orderId, orderNo, content, mScoreNumber, tagStr, isAnonymous, mIconlist);
                }else {
                    ToastUtil.showToastINFO(OrderCommentActivity.this,"请最少选择一个一张图片");
                    return;
                }
                 break;
        }
    }
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(OrderCommentActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .isWithVideoImage(true)// 图片和视频是否可以同选,只在ofAll模式下有效
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 关闭在AndroidQ下获取图片或视频宽高相反自动转换
                    .imageSpanCount(4)// 每行显示个数
                    .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                    .closeAndroidQChangeWH(true)//如果图片有旋转角度则对换宽高,默认为true
                    .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 如果视频有旋转角度则对换宽高,默认为false
                    .isAndroidQTransform(false)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && .isEnableCrop(false);有效,默认处理
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                    .selectionMode(PictureConfig.MULTIPLE)
                    .isPreviewImage(true)// 是否可预览图片
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .isEnableCrop(true)// 是否裁剪
                    .isCompress(true)// 是否压缩
                    .compressQuality(80)// 图片压缩后输出质量 0~ 100
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                    .isGif(false)// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .circleDimmedLayer(true)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .selectionData(mAdapter.getData())// 是否传入已选图片
                    .cutOutQuality(90)// 裁剪输出质量 默认100
                    .minimumCompressSize(100)// 小于多少kb的图片不压缩
                    .forResult(new MyResultCallback(mAdapter));
        }
    };

    @Override
    public void getOrderComment(BaseBean bean) {
        if (bean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            ToastUtil.showToastINFO(OrderCommentActivity.this, "评论成功");
            finishWitchAnimation();
        } else {
            ToastUtil.showToastINFO(OrderCommentActivity.this, bean.getMsg());
        }
    }

    @Override
    public void SetPersenter(Object persenter) {

    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {

    }

    /**
     * 返回结果回调
     */
    private static class MyResultCallback implements OnResultCallbackListener<LocalMedia> {
        private WeakReference<GridImageAdapter> mAdapterWeakReference;

        public MyResultCallback(GridImageAdapter adapter) {
            super();
            this.mAdapterWeakReference = new WeakReference<>(adapter);
        }

        @Override
        public void onResult(List<LocalMedia> result) {
            if (mAdapterWeakReference.get() != null) {
                mAdapterWeakReference.get().setList(result);
                mAdapterWeakReference.get().notifyDataSetChanged();
            }
            mIconlist = result;
        }

        @Override
        public void onCancel() {
        }
    }
}
